package com.paypalpay.util.pay;

import com.paypalpay.util.wx.HMACSHA256;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class OceanpaymentUtil {
    private static Logger logger = Logger.getLogger(OceanpaymentUtil.class);

    public static Map getNotifyResult(HttpServletRequest request) {
        String secureCode = "";
        String inputLine;
        String notifyXml = "";
        String resXml = "";
        try {
            while ((inputLine = request.getReader().readLine()) != null) {
                notifyXml += inputLine;
            }
            request.getReader().close();
        } catch (Exception e) {
            logger.debug("xml获取失败：" + e);
            e.printStackTrace();
        }
        System.out.println("接收到的xml：" + notifyXml);
        logger.debug("收到钱海异步回调：");
        logger.debug(notifyXml);

        String responseType = getXmlPara(notifyXml, "response_type");
        String account = getXmlPara(notifyXml, "account");
        String terminal = getXmlPara(notifyXml, "terminal");
        String signValue = getXmlPara(notifyXml, "signValue");
        String methods = getXmlPara(notifyXml, "methods");
        String orderNumber = getXmlPara(notifyXml, "order_number");
        String orderCurrency = getXmlPara(notifyXml, "order_currency");
        String orderAmount = getXmlPara(notifyXml, "order_amount");
        String orderNotes = getXmlPara(notifyXml, "order_notes");
        String cardNumber = getXmlPara(notifyXml, "card_number");
        String paymentId = getXmlPara(notifyXml, "payment_id");
        String paymentCountry = getXmlPara(notifyXml, "payment_country");
        String paymentAuthType = getXmlPara(notifyXml, "payment_authType");
        String paymentStatus = getXmlPara(notifyXml, "payment_status");
        String paymentDetails = getXmlPara(notifyXml, "payment_details");
        String paymentRisk = getXmlPara(notifyXml, "payment_risk");
        String paymentSolutions = getXmlPara(notifyXml, "payment_solutions");
        String authReason = getXmlPara(notifyXml, "auth_reason");
        String orderOperator = getXmlPara(notifyXml, "order_operator");

        //根据返回的xml计算签名
        String localSign =
                "account=" + account +
                        "terminal=" + terminal +
                        "order_number=" + orderNumber +
                        "order_currency=" + orderCurrency +
                        "order_amount=" + orderAmount +
                        "order_notes=" + orderNotes +
                        "card_number=" + cardNumber +
                        "payment_id=" + paymentId +
                        "payment_authType=" + paymentAuthType +
                        "payment_status=" + paymentStatus +
                        "payment_details=" + paymentDetails +
                        "payment_risk=" + paymentRisk +
                        "secureCode=" + secureCode;

        localSign = HMACSHA256.sha256_HMAC(localSign, secureCode).toUpperCase();
        logger.debug("通过回调数据计算本地签名是：" + localSign);
        logger.debug("钱海支付回调签名：" + signValue);

        if (!signValue.equals(localSign) || !"1".equals(paymentStatus)) {

            logger.error("验证签名失败或返回错误结果码");
        } else {
            logger.error("钱海支付成功");
            logger.debug("钱海支付成功，order_number(订单号)为：" + orderNumber);
            logger.debug("钱海支付成功，order_amount(金额)为：" + orderAmount);
            logger.debug("钱海支付成功，payment_status(支付结果)为：" + paymentStatus);

            //返回一个map,给接口提供参数
            Map<String, Object> returnMap = new HashMap<String, Object>();
            returnMap.put("orderNumber", orderNumber);
            returnMap.put("orderAmount", orderAmount);
            returnMap.put("paymentStatus", paymentStatus);

            returnMap.put("responseType", responseType);
            returnMap.put("account", account);
            returnMap.put("terminal", terminal);
            returnMap.put("signValue", signValue);
            returnMap.put("methods", methods);
            returnMap.put("orderCurrency", orderCurrency);
            returnMap.put("orderNotes", orderNotes);
            returnMap.put("cardNumber", cardNumber);
            returnMap.put("paymentId", paymentId);
            returnMap.put("paymentCountry", paymentCountry);
            returnMap.put("paymentAuthType", paymentAuthType);
            returnMap.put("paymentDetails", paymentDetails);
            returnMap.put("paymentRisk", paymentRisk);
            returnMap.put("paymentSolutions", paymentSolutions);
            returnMap.put("authReason", authReason);
            returnMap.put("orderOperator", orderOperator);

            return returnMap;

        }
        return null;
    }

    /**
     * 解析XML 获得名称为para的参数值
     *
     * @param xml
     * @param para
     * @return
     */
    public static String getXmlPara(String xml, String para) {
        int start = xml.indexOf("<" + para + ">");
        int end = xml.indexOf("</" + para + ">");

        if (start < 0 && end < 0) {
            return null;
        }
        return xml.substring(start + ("<" + para + ">").length(), end)
                .replace("<![CDATA[", "").replace("]]>", "");
    }
}
